import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:loading_animation_widget/loading_animation_widget.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_conversation.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_message.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_user_full_info.dart';
import 'package:tencent_cloud_chat_sdk/tencent_im_sdk_plugin.dart';
import 'package:tencent_desk_i18n_tool/language_json/strings.g.dart';
import 'package:tencentcloud_ai_desk_customer/base_widgets/tim_ui_kit_base.dart';
import 'package:tencentcloud_ai_desk_customer/base_widgets/tim_ui_kit_state.dart';
import 'package:tencentcloud_ai_desk_customer/business_logic/life_cycle/chat_life_cycle.dart';
import 'package:tencentcloud_ai_desk_customer/business_logic/view_models/tui_conversation_view_model.dart';
import 'package:tencentcloud_ai_desk_customer/customer_service/data/tencent_cloud_customer_data.dart';
import 'package:tencentcloud_ai_desk_customer/customer_service/plugin/components/message-customer-service.dart';
import 'package:tencentcloud_ai_desk_customer/customer_service/plugin/tencent_cloud_chat_customer_service_plugin.dart';
import 'package:tencentcloud_ai_desk_customer/customer_service/widgets/tencent_cloud_customer_message_tongue_item.dart';
import 'package:tencentcloud_ai_desk_customer/data_services/conversation/conversation_services.dart';
import 'package:tencentcloud_ai_desk_customer/data_services/core/core_services.dart';
import 'package:tencentcloud_ai_desk_customer/data_services/services_locatar.dart';
import 'package:tencentcloud_ai_desk_customer/tencentcloud_ai_desk_customer.dart';
import 'package:tencentcloud_ai_desk_customer/theme/tui_theme.dart';
import 'package:tencentcloud_ai_desk_customer/ui/controller/tim_uikit_chat_controller.dart';
import 'package:tencentcloud_ai_desk_customer/ui/views/TIMUIKitChat/TIMUIKItMessageList/TIMUIKitTongue/tim_uikit_chat_history_message_list_tongue.dart';
// import 'package:tencent_desk_i18n_tool/language_json/strings.g.dart';
import 'package:tencentcloud_ai_desk_customer/ui/views/TIMUIKitChat/TIMUIKItMessageList/tim_uikit_chat_history_message_list_item.dart';
import 'package:tencentcloud_ai_desk_customer/ui/views/TIMUIKitChat/TIMUIKitTextField/tim_uikit_more_panel.dart';
import 'package:tencentcloud_ai_desk_customer/ui/views/TIMUIKitChat/tim_uikit_chat_config.dart';
import 'package:yqmssa_app/config/app_config.dart';
import 'package:yqmssa_app/utils/shared_utils.dart';
import 'package:yqmssa_app/utils/tencent_im_utils.dart';
import 'package:yqmssa_app/utils/wx_utils.dart';
import 'package:yqmssa_app/views/splash_methods.dart';

class IntelligenceCustomerView extends StatefulWidget {
  final TencentCloudCustomerConfig config;
  final String customerServiceUserID;

  const IntelligenceCustomerView({
    super.key,
    this.customerServiceUserID = "@customer_service_account",
    required this.config,
  });

  @override
  State<IntelligenceCustomerView> createState() => _IntelligenceCustomerViewState();
}

class _IntelligenceCustomerViewState extends TIMUIKitState<IntelligenceCustomerView> {
  final TCustomerConversationViewModel _conversationViewModel = serviceLocator<TCustomerConversationViewModel>();
  final TCustomerConversationService _conversationService = serviceLocator<TCustomerConversationService>();
  final TencentCloudCustomerData _tencentCloudCustomerData = serviceLocator<TencentCloudCustomerData>();

  final TIMUIKitChatController _kitController = TIMUIKitChatController();

  V2TimConversation? _customerServiceConversation;
  String? _customerServiceTyping;

  late AppInitDM initData;

  @override
  void initState() {
    super.initState();
    if (AppConfig.appInitData.havePop == 1) {
      Future.delayed(const Duration(seconds: 1), tencentImUtils.inviteDialog);
    }
    init();
    setState(() {
      initData = AppConfig.appInitData;
    });
  }

  init() {
    TencentCloudAIDeskCustomer.getIMUIKitInstance().setTheme(
        theme: const TUITheme(
      chatBgColor: Color(0XFFF3F3F3),
      primaryColor: Color(0XFFFF6800),
      chatMessageItemFromSelfBgColor: Color(0XFFFF6800),
      chatMessageItemFromOthersBgColor: Colors.white,
      chatTimeDividerTextColor: Color(0XFFF3F3F3),
      textColor: Colors.white,
      adminColor: Color(0XFFFF6800),
      chatHeaderBgColor: Colors.white,
      appbarBgColor: Color(0XFFFF6800),
    ));
  }

  @override
  void didUpdateWidget(IntelligenceCustomerView oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.customerServiceUserID != widget.customerServiceUserID && TencentDeskUtils.checkString(widget.customerServiceUserID) != null) {
      _sendStartMessage(0);
    }
  }

  _sendStartMessage(int times) {
    final TDeskAppLocale language = widget.config.language ??
        TDesk_getCurrentDeviceLocaleInLocale(
            _tencentCloudCustomerData.tDeskDataCenter == TDeskDataCenter.mainlandChina ? TDeskAppLocale.zhHans : TDeskAppLocale.en);
    Future.delayed(const Duration(milliseconds: 50), () {
      try {
        TencentCloudChatCustomerServicePlugin.sendCustomerServiceStartMessage(_kitController.sendMessage, languageLocaleToDeskString[language] ?? "en");
      } catch (e) {
        if (times < 4) {
          Future.delayed(const Duration(milliseconds: 200), () {
            _sendStartMessage(times++);
          });
        }
      }
    });
  }

  Future<V2TimConversation> _loadConversation() async {
    final conversationID = "c2c_${widget.customerServiceUserID}";
    V2TimConversation? targetConversation =
        _conversationViewModel.getConversation(conversationID) ?? await _conversationService.getConversation(conversationID: conversationID);
    if (targetConversation == null) {
      V2TimUserFullInfo? userProfile;
      final userProfileRes = await TencentImSDKPlugin.v2TIMManager.getUsersInfo(userIDList: [
        widget.customerServiceUserID,
      ]);
      if (userProfileRes.data != null && userProfileRes.data!.isNotEmpty) {
        userProfile = userProfileRes.data!.first;
      }
      targetConversation = V2TimConversation(
        conversationID: conversationID,
        userID: widget.customerServiceUserID,
        faceUrl: TencentDeskUtils.checkString(userProfile?.faceUrl),
        showName: TencentDeskUtils.checkString(userProfile?.nickName) ??
            TencentDeskUtils.checkString(userProfile?.userID) ??
            TencentDeskUtils.checkString(widget.customerServiceUserID) ??
            TDesk_t("智能客服"),
        type: 1,
      );
    }
    _customerServiceConversation = targetConversation;
    _sendStartMessage(0);
    return targetConversation;
  }

  Widget? _quickMessagesWidget() {
    return SizedBox(
      height: 44,
      child: SingleChildScrollView(
        scrollDirection: Axis.horizontal,
        child: Wrap(
          spacing: 15,
          children: [
            const SizedBox(width: 1),
            if (initData.haveCall == 1)
              InkWell(
                onTap: tencentImUtils.tellPhone,
                child: Container(
                  alignment: Alignment.center,
                  padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(22),
                    color: Colors.white,
                  ),
                  child: Row(
                    children: [
                      Image.asset(AppConfig.imagePath("phone.png"), width: 22),
                      const SizedBox(width: 8),
                      const Text(
                        "拨打电话",
                        style: TextStyle(color: Colors.black, fontWeight: FontWeight.w500),
                      ),
                    ],
                  ),
                ),
              ),
            if (initData.addWxButton?.addWxView == 1)
              InkWell(
                onTap: tencentImUtils.addWeChat,
                child: Container(
                  alignment: Alignment.center,
                  padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(32),
                  ),
                  child: Row(
                    children: [
                      Image.asset(AppConfig.imagePath("wei.png"), width: 22),
                      const SizedBox(width: 8),
                      Text(
                        (initData.addWxButton?.chatWeText ?? "").isNotEmpty ? (initData.addWxButton?.chatWeText ?? "") : "添加微信",
                        style: const TextStyle(color: Colors.black, fontWeight: FontWeight.w500),
                      ),
                    ],
                  ),
                ),
              ),
          ],
        ),
      ),
    );
  }

  @override
  Widget tuiBuild(BuildContext context, TUIKitBuildValue value) {
    final theme = value.theme;
    return FutureBuilder<V2TimConversation>(
      future: _loadConversation(),
      builder: (BuildContext context, AsyncSnapshot<V2TimConversation> snapshot) {
        final targetConversation = snapshot.data ?? _customerServiceConversation;
        return targetConversation != null
            ? TencentCloudCustomerMessage(
                conversation: targetConversation,
                customAppBar: Container(
                  color: Colors.white,
                  padding: EdgeInsets.only(
                    top: MediaQuery.paddingOf(context).top + 8,
                    left: 16,
                    right: 10,
                    bottom: 20,
                  ),
                  child: Stack(
                    children: [
                      Container(
                        margin: const EdgeInsets.only(
                          right: 6,
                        ),
                        child: GestureDetector(
                          onTap: () {
                            FocusScope.of(context).unfocus();
                            Navigator.pop(context);
                          },
                          child: const ColorFiltered(
                              colorFilter: ColorFilter.mode(
                                Colors.black,
                                BlendMode.srcIn,
                              ),
                              child: Icon(Icons.arrow_back_ios_new_rounded)),
                        ),
                      ),
                      const Center(
                        child: Text(
                          "逾期小助理",
                          style: TextStyle(
                            fontSize: 16,
                            color: Colors.black87,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                inputTopBuilder: _quickMessagesWidget(),
                tongueItemBuilder: (VoidCallback onClick, MessageListTongueType valueType, int unreadCount) => TencentCloudCustomerTongueItem(
                  onClick: onClick,
                  valueType: valueType,
                  previousCount: 0,
                  unreadCount: unreadCount,
                  atNum: "",
                ),
                conversationShowName: _customerServiceTyping ?? targetConversation.showName,
                lifeCycle: ChatLifeCycle(
                  newMessageWillMount: (V2TimMessage message) async {
                    if (TencentCloudChatCustomerServicePlugin.isCustomerServiceMessage(message)) {
                      if (TencentCloudChatCustomerServicePlugin.isTypingCustomerServiceMessage(message)) {
                        setState(() {
                          _customerServiceTyping = TDesk_t("对方正在输入中...");
                        });
                      }
                    } else {
                      setState(() {
                        _customerServiceTyping = null;
                      });
                    }
                    return message;
                  },
                  messageShouldMount: (V2TimMessage message) {
                    if (TencentCloudChatCustomerServicePlugin.isCustomerServiceMessage(message)) {
                      return !TencentCloudChatCustomerServicePlugin.isCustomerServiceMessageInvisible(message) && !(message.isSelf ?? true);
                    }
                    return true;
                  },
                ),
                morePanelConfig: MorePanelConfig(
                  showVideoCall: false,
                  showVoiceCall: false,
                ),
                toolTipsConfig: ToolTipsConfig(
                  showForwardMessage: false,
                  showMultipleChoiceMessage: false,
                  showTranslation: false,
                ),
                config: TIMUIKitChatConfig(
                  isUseMessageReaction: false,
                  isShowAvatar: false,
                  textHeight: kTextHeightNone,
                  isShowReadingStatus: widget.config.useMessageReadReceipt ?? false,
                  isAllowSoundMessage: false,
                  // isAllowShowMorePanel: false,
                  stickerPanelConfig: StickerPanelConfig(
                    useTencentCloudChatStickerPackage: true,
                    useQQStickerPackage: false,
                    useTencentCloudChatStickerPackageOldKeys: false,
                    unicodeEmojiList: [],
                    customStickerPackages: [],
                  ),
                ),
                messageItemBuilder: MessageItemBuilder(
                  messageRowBuilder: (
                    V2TimMessage message,
                    Widget messageWidget,
                    Function onScrollToIndex,
                    bool isNeedShowJumpStatus,
                    VoidCallback clearJumpStatus,
                    Function onScrollToIndexBegin,
                  ) {
                    if (TencentCloudChatCustomerServicePlugin.isCustomerServiceMessage(message)) {
                      return Container(
                        padding: const EdgeInsets.symmetric(horizontal: 16),
                        margin: const EdgeInsets.only(
                          bottom: 16,
                        ),
                        child: Row(
                          children: [
                            Expanded(
                              child: messageWidget,
                            )
                          ],
                        ),
                      );
                    }
                    return null;
                  },
                  customMessageItemBuilder: (message, isShowJump, clearJump) {
                    final data = jsonDecode(message.customElem?.data ?? "");
                    if (data["title"] != null) {
                      return InkWell(
                        onTap: () {
                          WechatUtils.pushWxXcx(sharedUtils.service?.id ?? 0);
                        },
                        child: Container(
                          padding: const EdgeInsets.all(12),
                          decoration: BoxDecoration(
                            gradient: const LinearGradient(
                              colors: [
                                Color(0XFFFFDFC1),
                                Color(0XFFFFD4AF),
                              ],
                              begin: Alignment(-1, 0),
                              end: Alignment(1, 0),
                            ),
                            border: Border.all(width: 1, color: Colors.yellowAccent),
                            borderRadius: const BorderRadius.only(
                              topRight: Radius.circular(12),
                              bottomLeft: Radius.circular(12),
                              bottomRight: Radius.circular(12),
                            ),
                          ),
                          child: Row(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              Image.asset(AppConfig.imagePath("wei.png"), width: 44),
                              const SizedBox(width: 12),
                              Column(
                                mainAxisSize: MainAxisSize.min,
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(
                                    data["title"] ?? "法务老师",
                                    style: const TextStyle(color: Color(0XFF683C14), fontWeight: FontWeight.bold),
                                  ),
                                  Text(
                                    data["description"] ?? "点击添加法务老师微信",
                                    style: const TextStyle(color: Color(0XFF683C14)),
                                  ),
                                ],
                              )
                            ],
                          ),
                        ),
                      );
                    }

                    if (TencentCloudChatCustomerServicePlugin.isCustomerServiceMessage(message)) {
                      return MessageCustomerService(
                        message: message,
                        textPadding: const EdgeInsets.all(16),
                        messageBackgroundColor: Colors.white,
                        theme: theme,
                        isShowJumpState: isShowJump,
                        sendMessage: _kitController.sendMessage,
                      );
                    }
                    return null;
                  },
                ),
                controller: _kitController,
              )
            : Column(
                children: [
                  Expanded(
                    child: Center(
                      child: LoadingAnimationWidget.staggeredDotsWave(
                        color: theme.weakTextColor ?? Colors.grey,
                        size: 28,
                      ),
                    ),
                  )
                ],
              );
      },
    );
  }
}
